package com.smoed.common.utilities;

import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public final class StringUtils {
    private StringUtils() {
    }

    public static final String TAB = "    "; // four spaces
    public static final String NEWLINE = System.getProperty("line.separator");

    public static String delimitString(Iterable<String> strings, String delimiter) {
        Iterator<String> i = strings.iterator();
        if (! i.hasNext())
            return "";

        StringBuilder sb = new StringBuilder();
        for (;;) {
            String str = i.next();
            sb.append(str);
            if (! i.hasNext())
                return sb.toString();
            sb.append(delimiter);
        }
    }

    public static String toCamelCase(String str, String delimiter) {
        StringBuilder camel = new StringBuilder();
        for (String subStr : str.split(delimiter)) {
            camel.append(subStr.substring(0, 1).toUpperCase());
            camel.append(subStr.substring(1));
        }
        return camel.toString();
    }

    public static String toDatabaseNamingConvention(String str) {
        char[] chars = str.toCharArray();
        StringBuilder dbString = new StringBuilder();
        dbString.append(Character.toLowerCase(chars[0]));
        for(int i = 1; i < chars.length; i++) {
            char c = chars[i];
            if (Character.isUpperCase(c)) {
                dbString.append("_").append(Character.toLowerCase(c));
            } else {
                dbString.append(c);
            }
        }

        return dbString.toString();
    }

    public static int countMatches(String str, Pattern pattern) {
        int count = 0;

        final Matcher m = pattern.matcher(str);
        while (m.find()) {
            count++;
        }

        return count;
    }

    public static String replace(String sourceString, Pattern pattern, String replaceString) {
        return pattern.matcher(sourceString).replaceAll(replaceString);
    }

    private static final Pattern NON_ASCII_PATTERN = Pattern.compile("[^\\p{ASCII}]");

    public static String removeNonAsciiCharacters(String sourceString) {
        return replace(sourceString, NON_ASCII_PATTERN, "");
    }

    public static int getNumCharOccurrences(String str, char c) {
        int count = 0;
        for (int i=0; i < str.length(); i++) {
            if (str.charAt(i) == c) {
                count++;
            }
        }
        return count;
    }
}
